<?php

namespace App\Task\v1_1_0;

use App\Helpers\EventUtil;
use App\Model\CallBase;
use App\Model\Message;
use App\Model\Service\ConsumeService;
use App\Model\UserFreeCall;
use App\Model\VideoCall;
use App\Model\VoiceCall;
use Hyperf\Crontab\Annotation\Crontab;

/**
 * 天天福利 - 正在通话的语聊记录（时长和费用）
 * @Crontab(name="CheckFreeCallTask", rule="*\/1 * * * * *", callback="execute", memo="检测新手福利通话",singleton=false, enable=true)
 */
class CheckFreeCallTask
{
    public function execute()
    {
//        $this->checkCalls(VideoCall::CALL_TYPE);
//        $this->checkCalls(VoiceCall::CALL_TYPE);
    }

    /**
     * 检查通话
     */
    function checkCalls($callType = VoiceCall::CALL_TYPE)
    {
        $callCls = $callType == VoiceCall::CALL_TYPE ? VoiceCall::class : VideoCall::class;
        //获取当前正在通话的语聊记录
        $callingLogs = $callCls::getCallsForDailyFree(CallBase::STATUS_ING);
        $count = count($callingLogs);
        log_info(__CLASS__ . "==docheck==CallType:{$callType}==Count:{$count}");
        if ($count == 0) return;
        array_walk($callingLogs, function ($callingLog) use ($callType, $callCls) {
            //根据话单ID获取免费券记录
            $freeCallLog = UserFreeCall::checkByCallId($callingLog['id'], $callType);
            //没有免费券记录
            // if (!$freeCallLog) {
            // $callCls::where('id', $callingLog['id'])->update(['status' => CallBase::STATUS_ERR_HANGUP]);
            // Message::sendSlient($callingLog['user_id'], 'HANGUP_CALL', ['tip' => '还未获取免费券福利～']);
            // log_info(__CLASS__ . "==no_freecall==CallType:{$callType}==LogId:{$callingLog['id']}");
            // return;
            // }

            //已经拨打时间
            $callSeconds = time() - $callingLog['answer_time'];

            //免费时间
            $freeSeconds = $freeCallLog ? $freeCallLog->free_minutes * 60 : 60;

            if ($callSeconds >= ($freeSeconds - 10)) {
                //结算单
                $this->endCall($callingLog, $callCls, $freeCallLog);

                //福利时间用完，中止通话- 透传消息
                Message::sendSlient($callingLog['user_id'], 'HANGUP_CALL', ['tip' => '你的免费福利时长已经用完了，该次通话结束~']);
                Message::sendSlient($callingLog['chat_user_id'], 'HANGUP_CALL', ['tip' => '对方免费福利时长已经用完了，该次通话结束~']);

                //发系统消息
                Message::pushOfficialMsg($callingLog['user_id'], "你的免费通话时长已用完，通话已结束~");

                log_info(__CLASS__ . "==overtime==CallType:{$callType}==TotalTime:{$callSeconds}s==LogId:{$callingLog['id']}");
            } elseif($callSeconds >= ($freeSeconds - 15)){
//                Message::sendSlient($callingLog['chat_user_id'], 'FREE_BALANCE_TIP', ['title' => '温馨提示','sub_title' => '免费通话即将结束，充值后可与她继续畅聊哦~']);
            } else {
                log_info(__CLASS__ . "==passcheck==CallType:{$callType}==TotalTime:{$callSeconds}s==LogId:{$callingLog['id']}");
            }
            return;
        });
    }

    /**
     * 结算话单
     */
    function endCall($callRecord = null, $callCls = VideoCall::class, $freeCallLog = null)
    {
        if (is_array($callRecord)) $callRecord = $callCls::find($callRecord['id']);
        //离开频道，更新话单状态
        $callRecord = CallBase::channelOutUpdate($callRecord, 1);
        if (!$callRecord) return;
        //通话消费处理
        ConsumeService::settleCallForFree($callRecord, $callCls::CALL_TYPE);
        //免费券状态更新
        $freeCallLog && $freeCallLog->update([
            'status' => UserFreeCall::STATUS_USED,
            'used_minutes' => $freeCallLog->free_minutes,
        ]);
        //挂断事件分发
        EventUtil::dispatchHangup(
            $callRecord,
            $callCls::CALL_TYPE == VideoCall::CALL_TYPE ? 'video' : 'voice'
        );
        log_info(__CLASS__ . "=={$callCls}==EndCall==LogId:{$callRecord->id}");
    }
}
